package ee.subjects.frontend.controller.command.personCommands;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ee.subjects.backend.model.data.Person;
import ee.subjects.backend.services.PersonService;
import ee.subjects.backend.services.PersonServiceImpl;
import ee.subjects.frontend.controller.command.Command;

public class AllPersonsCommand implements Command {

	@Override
	public int execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// If task to delete
		if(request.getParameter("task")!=null){
			this.finishTask(request);
		}
		

		PersonService personService = new PersonServiceImpl();
		List<Person> allPersons = personService.getAllPersons();
		
		request.setAttribute ("AllPersons", allPersons);

		return 1;
	}

	private void finishTask(HttpServletRequest request) {
		if(request.getParameter("task").equals("delete")){
			int personToDelete = Integer.parseInt(request.getParameter("id"));
			
			PersonService personService = new PersonServiceImpl();
			personService.deletePersonAndItsRelatedData(personToDelete);
		}
	}

}
